<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.1.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.1.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.1.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.1.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '6.1.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="此为龙果学院课程笔记，记录以供以后翻看 上亿流量的商品详情页系统的多级缓存架构很多人以为做个缓存其实就是用一下redis访问一下就可以了，这只是简单的缓存使用方式。做复杂的缓存，支撑电商等复杂的场景下的高并发的缓存，遇到的问题非常非常之多，绝对不是说简单的访问一下redis就可以了。">
<meta name="keywords" content="多级缓存架构">
<meta property="og:type" content="article">
<meta property="og:title" content="高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案">
<meta property="og:url" content="http://www.saily.top/2018/02/18/cache04/index.html">
<meta property="og:site_name" content="帆的博客">
<meta property="og:description" content="此为龙果学院课程笔记，记录以供以后翻看 上亿流量的商品详情页系统的多级缓存架构很多人以为做个缓存其实就是用一下redis访问一下就可以了，这只是简单的缓存使用方式。做复杂的缓存，支撑电商等复杂的场景下的高并发的缓存，遇到的问题非常非常之多，绝对不是说简单的访问一下redis就可以了。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://www.saily.top/img/cache/三级缓存架构图.png">
<meta property="og:image" content="http://www.saily.top/img/cache/多个缓存服务实例分布式重建的并发冲突问题.png">
<meta property="og:image" content="http://www.saily.top/img/cache/基于zookeeper分布式锁的冲突解决方案.png">
<meta property="og:image" content="http://www.saily.top/img/cache/复杂的数据库+缓存双写一致保障方案.png">
<meta property="og:updated_time" content="2018-08-25T07:42:47.596Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案">
<meta name="twitter:description" content="此为龙果学院课程笔记，记录以供以后翻看 上亿流量的商品详情页系统的多级缓存架构很多人以为做个缓存其实就是用一下redis访问一下就可以了，这只是简单的缓存使用方式。做复杂的缓存，支撑电商等复杂的场景下的高并发的缓存，遇到的问题非常非常之多，绝对不是说简单的访问一下redis就可以了。">
<meta name="twitter:image" content="http://www.saily.top/img/cache/三级缓存架构图.png">



  <link rel="alternate" href="/atom.xml" title="帆的博客" type="application/atom+xml" />




  <link rel="canonical" href="http://www.saily.top/2018/02/18/cache04/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案 | 帆的博客</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">帆的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">扬帆起航</p>
      
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>




<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-about">
    <a href="/about/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />归档</a>
  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.saily.top/2018/02/18/cache04/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="杨帆">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/img/photo/bug.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="帆的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">高可用缓存架构实战4-多级缓存架构.高并发读写方案.nginx流量分发方案.ZK分布式锁解决并发冲突方案
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            
                
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-02-18T19:45:55+08:00">2月 18 2018</time>
            

            
            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/categories/高可用缓存架构实战/" itemprop="url" rel="index"><span itemprop="name">高可用缓存架构实战</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="post-meta-item-icon"
            >
            <i class="fa fa-eye"></i>
             阅读次数： 
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>此为龙果学院课程笔记，记录以供以后翻看</p>
<h2 id="上亿流量的商品详情页系统的多级缓存架构"><a href="#上亿流量的商品详情页系统的多级缓存架构" class="headerlink" title="上亿流量的商品详情页系统的多级缓存架构"></a>上亿流量的商品详情页系统的多级缓存架构</h2><p>很多人以为做个缓存其实就是用一下redis访问一下就可以了，这只是简单的缓存使用方式。做复杂的缓存，支撑电商等复杂的场景下的高并发的缓存，遇到的问题非常非常之多，绝对不是说简单的访问一下redis就可以了。<br><a id="more"></a><br>通常采用三级缓存：<strong>nginx本地缓存+redis分布式缓存+tomcat堆缓存的多级缓存架构</strong></p>
<p><img src="/img/cache/三级缓存架构图.png" alt=""></p>
<p>时效性要求非常高的数据：<strong>库存</strong></p>
<p>一般来说，显示的库存都是时效性要求会相对高一些，因为随着商品的不断的交易，库存会不断的变化。当然，我们就希望当库存变化的时候，尽可能更快将库存显示到页面上去，而不是说等了很长时间，库存才反应到页面上去。</p>
<p>时效性要求不高的数据：<strong>商品的基本信息（名称. 颜色. 版本. 规格参数，等等）</strong>，时效性要求不高的数据，就还好，比如说你现在改变了商品的名称，稍微晚个几分钟反应到商品页面上，也是可以接受的。</p>
<p>商品价格/库存等时效性要求高的数据，这种数据不多，相关的服务系统每次发生了变更的时候，直接采取数据库和redis缓存双写的方案，这样缓存的时效性最高。</p>
<p>商品基本信息等时效性不高的数据，而且种类繁多，来自多种不同的系统，采取MQ异步通知的方式，写一个数据生产服务，监听MQ消息，然后异步拉取服务的数据，更新tomcat jvm缓存+redis缓存。</p>
<p>流程：<strong>nginx+lua脚本做页面动态生成的工作</strong>，每次请求过来，优先从nginx本地缓存中提取各种数据，结合页面模板，生成需要的页面。如果nginx本地缓存过期了，那么就从nginx到<strong>redis</strong>中去拉取数据，更新到nginx本地。如果redis中也被LRU算法清理掉了，那么就从nginx走http接口到后端的服务中拉取数据，数据生产服务中，先在本地<strong>tomcat里的jvm堆缓存（ehcache）</strong>中找，如果也被LRU清理掉了，那么就重新发送请求到源头的服务中去拉取数据，然后<strong>再次更新tomcat堆内存缓存+redis缓存，并返回数据给nginx，nginx缓存到本地。</strong></p>
<h3 id="多级缓存架构中每一层的意义"><a href="#多级缓存架构中每一层的意义" class="headerlink" title="多级缓存架构中每一层的意义"></a>多级缓存架构中每一层的意义</h3><p><strong>nginx本地缓存</strong>，抗的是热数据的高并发访问，一般来说，商品的购买总是有热点的，比如每天购买iphone. nike. 海尔等知名品牌的东西的人，总是比较多的。这些热数据，由于经常被访问，利用nginx本地缓存，所以可以被锁定在nginx的本地缓存内。大量的热数据的访问，就会被保留在nginx本地缓存内，那么对这些热数据的大量访问，就直接走nginx就可以了。那么大量的访问，直接就可以走到nginx就行了，不需要走后续的各种网络开销了。</p>
<p><strong>redis分布式大规模缓存</strong>，抗的是很高的离散访问，支撑海量的数据，高并发的访问，高可用的服务。redis缓存最大量最完整的数据，可能1T+数据; 支撑高并发的访问，QPS最高到几十万; 可用性需要非常好，提供非常稳定的服务。nginx本地内存有限，也就能cache住部分热数据，除了各种iphone. nike等热数据，其他相对不那么热的数据，可能流量会经常走到redis那里。利用redis cluster的多master写入，横向扩容，1T+以上海量数据支持，几十万的读写QPS，99.99%高可用性都没有问题，那么就可以抗住大量的离散访问请求。</p>
<p><strong>tomcat jvm堆内存缓存</strong>，主要是抗redis大规模灾难的情况，如果redis出现了大规模的宕机，导致nginx大量流量直接涌入数据生产服务，那么最后的tomcat堆内存缓存至少可以再抗一下，不至于让数据库直接裸奔。同时tomcat jvm堆内存缓存，也可以抗住redis没有cache住的最后那少量的部分缓存。</p>
<h3 id="多级缓存架构项目实例源码"><a href="#多级缓存架构项目实例源码" class="headerlink" title="多级缓存架构项目实例源码"></a>多级缓存架构项目实例源码</h3><p>时效性要求不高的数据，采取的是异步更新缓存的策略。缓存数据生产服务，监听一个消息队列，然后数据源服务（商品信息管理服务）发生了数据变更之后，就将数据变更的消息推送到消息队列中。缓存数据生产服务可以去消费这个数据变更的消息，然后根据消息的指示提取一些参数，然后调用对应的数据源服务的接口拉取数据，这个时候一般是从mysql库中拉取的。</p>
<p>这里消息中间件，我们使用<code>kafka</code>，<a href="http://www.saily.top/2018/02/20/cache04-2/">zookeeper+kafka集群的安装部署</a></p>
<p>项目源码地址：<a href="https://github.com/sail-y/eshop-cache" target="_blank" rel="noopener">https://github.com/sail-y/eshop-cache</a></p>
<h3 id="Nginx层缓存"><a href="#Nginx层缓存" class="headerlink" title="Nginx层缓存"></a>Nginx层缓存</h3><p>前面三层缓存架构中的本地堆缓存+redis分布式缓存都做好了，接下来就要来做三级缓存中的nginx那一层的缓存了。一般默认会部署多个nginx，在里面都会放一些缓存，默认情况下，此时缓存命中率是比较低的，因为流量会均分。</p>
<p><strong>如何提升缓存命中率？</strong></p>
<p>分发层+应用层，双层nginx。</p>
<p>分发层nginx，负责流量分发的逻辑和策略，它可以用lua脚本开发一些规则，比如根据productId去进行hash，然后对后端的nginx数量取模，将某一个商品的访问的请求，就固定路由到一个nginx后端服务器上去，保证只会从redis中获取一次缓存数据，再次请求全都是走nginx本地缓存了。</p>
<p>后端的nginx服务器，就称之为应用服务器; 最前端的nginx服务器，被称之为分发服务器。看似很简单，其实很有用，在实际的生产环境中，可以大幅度提升你的nginx本地缓存这一层的命中率，大幅度减少redis后端的压力，提升性能。</p>
<p>这里会采用OpenResty的方式去部署nginx，而且会写一个nginx+lua开发的一个hello world。</p>
<h4 id="部署第一个nginx，作为应用层nginx"><a href="#部署第一个nginx，作为应用层nginx" class="headerlink" title="部署第一个nginx，作为应用层nginx"></a>部署第一个nginx，作为应用层nginx</h4><p>我这里部署到我机器上192.168.2.201，教程参考<a href="http://jinnianshilongnian.iteye.com/blog/2186270" target="_blank" rel="noopener">http://jinnianshilongnian.iteye.com/blog/2186270</a></p>
<h4 id="部署openresty"><a href="#部署openresty" class="headerlink" title="部署openresty"></a>部署openresty</h4><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line">yum install -y readline-devel pcre-devel openssl-devel gcc</span><br><span class="line"></span><br><span class="line">mkdir -p /usr/servers  </span><br><span class="line"><span class="built_in">cd</span> /usr/servers/</span><br><span class="line"></span><br><span class="line">wget http://openresty.org/download/ngx_openresty-1.7.7.2.tar.gz  </span><br><span class="line">tar -xzvf ngx_openresty-1.7.7.2.tar.gz  </span><br><span class="line"><span class="built_in">cd</span> /usr/servers/ngx_openresty-1.7.7.2/</span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> bundle/LuaJIT-2.1-20150120/  </span><br><span class="line">make clean &amp;&amp; make &amp;&amp; make install  </span><br><span class="line">ln -sf luajit-2.1.0-alpha /usr/<span class="built_in">local</span>/bin/luajit</span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> bundle  </span><br><span class="line">wget https://github.com/FRiCKLE/ngx_cache_purge/archive/2.3.tar.gz  </span><br><span class="line">tar -xvf 2.3.tar.gz  </span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> bundle  </span><br><span class="line">wget https://github.com/yaoweibin/nginx_upstream_check_module/archive/v0.3.0.tar.gz  </span><br><span class="line">tar -xvf v0.3.0.tar.gz  </span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> /usr/servers/ngx_openresty-1.7.7.2  </span><br><span class="line">./configure --prefix=/usr/servers --with-http_realip_module  --with-pcre  --with-luajit --add-module=./bundle/ngx_cache_purge-2.3/ --add-module=./bundle/nginx_upstream_check_module-0.3.0/ -j2  </span><br><span class="line">make &amp;&amp; make install </span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> /usr/servers/  </span><br><span class="line">ll</span><br><span class="line"></span><br><span class="line">/usr/servers/luajit</span><br><span class="line">/usr/servers/lualib</span><br><span class="line">/usr/servers/nginx</span><br><span class="line">/usr/servers/nginx/sbin/nginx -v</span><br></pre></td></tr></table></figure>
<p>启动nginx: <code>/usr/servers/nginx/sbin/nginx</code></p>
<h4 id="nginx-lua开发的hello-world"><a href="#nginx-lua开发的hello-world" class="headerlink" title="nginx+lua开发的hello world"></a>nginx+lua开发的hello world</h4><pre><code>vi /usr/servers/nginx/conf/nginx.conf
</code></pre><p>在http部分添加：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">lua_package_path &quot;/usr/servers/lualib/?.lua;;&quot;;  </span><br><span class="line">lua_package_cpath &quot;/usr/servers/lualib/?.so;;&quot;;</span><br></pre></td></tr></table></figure>
<p><code>/usr/servers/nginx/conf</code>下，创建一个<code>lua.conf</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">server &#123;  </span><br><span class="line">    listen       80;  </span><br><span class="line">    server_name  _;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在nginx.conf的http部分添加：</p>
<pre><code>include lua.conf;
</code></pre><p>验证配置是否正确：</p>
<pre><code>/usr/servers/nginx/sbin/nginx -t
</code></pre><p>在lua.conf的server部分添加：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">location /lua &#123;  </span><br><span class="line">    default_type &apos;text/html&apos;;  </span><br><span class="line">    content_by_lua &apos;ngx.say(&quot;hello world&quot;)&apos;;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>验证配置是否正确：</p>
<pre><code>/usr/servers/nginx/sbin/nginx -t  
</code></pre><p>重新nginx加载配置</p>
<pre><code>/usr/servers/nginx/sbin/nginx -s reload  
</code></pre><p>访问： <a href="http://192.168.2.201/lua" target="_blank" rel="noopener">http://192.168.2.201/lua</a></p>
<p>成功输出 hello world</p>
<hr>
<p>接下来替换成lua脚本文件执行</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">mkdir /usr/servers/nginx/conf/lua/</span><br><span class="line">vi /usr/servers/nginx/conf/lua/test.lua</span><br><span class="line">ngx.say(<span class="string">"hello world"</span>);</span><br></pre></td></tr></table></figure>
<p>修改lua.conf</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">location /lua &#123;  </span><br><span class="line">    default_type &apos;text/html&apos;;  </span><br><span class="line">    content_by_lua_file conf/lua/test.lua; </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>验证配置是否正确：</p>
<pre><code>/usr/servers/nginx/sbin/nginx -t  
</code></pre><p>重新nginx加载配置</p>
<pre><code>/usr/servers/nginx/sbin/nginx -s reload  
</code></pre><hr>
<p>查看异常日志</p>
<pre><code>tail -f /usr/servers/nginx/logs/error.log
</code></pre><h4 id="工程化的nginx-lua项目结构"><a href="#工程化的nginx-lua项目结构" class="headerlink" title="工程化的nginx+lua项目结构"></a>工程化的nginx+lua项目结构</h4><p>刚才只是写了一个hello world，在正式的项目中，脚本的目录结构一般是下面这样：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">hello</span><br><span class="line">    hello.conf     </span><br><span class="line">    lua              </span><br><span class="line">      hello.lua</span><br><span class="line">    lualib            </span><br><span class="line">      *.lua</span><br><span class="line">      *.so</span><br></pre></td></tr></table></figure>
<p>放在/usr/hello目录下，不会放在nginx所在文件夹里。</p>
<p>配置如下：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">mkdir -p /usr/hello/lua</span><br><span class="line"><span class="built_in">echo</span> <span class="string">'ngx.say("hello world");'</span> &gt;&gt; /usr/hello/lua/hello.lua</span><br><span class="line">cp -r /usr/servers/lualib /usr/hello</span><br><span class="line"></span><br><span class="line">vi /usr/hello/hello.conf</span><br><span class="line"></span><br><span class="line">server &#123;  </span><br><span class="line">    listen       80;  </span><br><span class="line">    server_name  _;  </span><br><span class="line">  </span><br><span class="line">    location /hello &#123;  </span><br><span class="line">        default_type <span class="string">'text/html'</span>;  </span><br><span class="line">        content_by_lua_file /usr/hello/lua/hello.lua;  </span><br><span class="line">    &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>–</p>
<p>修改<code>nginx.conf</code></p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">vi /usr/servers/nginx/conf/nginx.conf</span><br><span class="line"></span><br><span class="line">worker_processes  2;  </span><br><span class="line"></span><br><span class="line">error_log  logs/error.log;  </span><br><span class="line"></span><br><span class="line">events &#123;  </span><br><span class="line">    worker_connections  1024;  </span><br><span class="line">&#125;  </span><br><span class="line"></span><br><span class="line">http &#123;  </span><br><span class="line">    include       mime.types;  </span><br><span class="line">    default_type  text/html;  </span><br><span class="line">  </span><br><span class="line">    lua_package_path <span class="string">"/usr/hello/lualib/?.lua;;"</span>;  </span><br><span class="line">    lua_package_cpath <span class="string">"/usr/hello/lualib/?.so;;"</span>; </span><br><span class="line">    include /usr/hello/hello.conf;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>–</p>
<p>验证配置是否正确：</p>
<pre><code>/usr/servers/nginx/sbin/nginx -t  
</code></pre><p>重新nginx加载配置</p>
<pre><code>/usr/servers/nginx/sbin/nginx -s reload  
</code></pre><p>如法炮制，在另外一个机器上，也用OpenResty部署一个nginx。</p>
<h4 id="开发和部署流量分发层"><a href="#开发和部署流量分发层" class="headerlink" title="开发和部署流量分发层"></a>开发和部署流量分发层</h4><p>我在eshop-cache02和eshop-cache03上都部署好了openresty。现在用eshop-cache01和eshop-cache02作为应用层nginx服务器，用eshop-cache03作为分发层nginx。</p>
<p>现在在eshop-cache03，也就是分发层nginx中，编写lua脚本，完成基于商品id的流量分发策略：</p>
<ol>
<li>获取请求参数，比如productId</li>
<li>对productId进行hash</li>
<li>hash值对应用服务器数量取模，获取到一个应用服务器</li>
<li>利用http发送请求到应用层nginx</li>
<li>获取响应后返回</li>
</ol>
<p>这个就是基于商品id的定向流量分发的策略，lua脚本来编写和实现。作为一个流量分发的nginx，会发送http请求到后端的应用nginx上面去，所以要先引入lua http lib包。</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> /usr/hello/lualib/resty/  </span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http_headers.lua  </span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua</span><br></pre></td></tr></table></figure>
<p>然后我们编辑流量分发的代码：</p>
<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">local</span> uri_args = ngx.req.get_uri_args()</span><br><span class="line"><span class="keyword">local</span> productId = uri_args[<span class="string">"productId"</span>]</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> hosts = &#123;<span class="string">"192.168.2.201"</span>, <span class="string">"192.168.2.202"</span>&#125;</span><br><span class="line"><span class="keyword">local</span> hash = ngx.crc32_long(productId)</span><br><span class="line"><span class="keyword">local</span> index = (hash % <span class="number">2</span>) + <span class="number">1</span></span><br><span class="line">backend = <span class="string">"http://"</span>..hosts[index]</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> requestPath = uri_args[<span class="string">"requestPath"</span>]</span><br><span class="line">requestPath = <span class="string">"/"</span>..requestPath..<span class="string">"?productId="</span>..productId</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> http = <span class="built_in">require</span>(<span class="string">"resty.http"</span>)</span><br><span class="line"><span class="keyword">local</span> httpc = http.new()</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> resp, err = httpc:request_uri(backend, &#123;</span><br><span class="line">    method = <span class="string">"GET"</span>,</span><br><span class="line">    <span class="built_in">path</span> = requestPath</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> <span class="keyword">not</span> resp <span class="keyword">then</span></span><br><span class="line">   ngx.say(<span class="string">"request error :"</span>, err)</span><br><span class="line">   <span class="keyword">return</span></span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line">ngx.say(resp.body)</span><br><span class="line"></span><br><span class="line">httpc:<span class="built_in">close</span>()</span><br></pre></td></tr></table></figure>
<p>访问测试：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">/usr/servers/nginx/sbin/nginx -s reload</span><br><span class="line">http://192.168.2.203/hello?productId=5&amp;requestPath=hello</span><br><span class="line">hello world. this is eshop-cache01</span><br></pre></td></tr></table></figure>
<p>基于商品id的定向流量分发策略的lua脚本就开发完了。经过测试可以看到，如果请求的是固定的某一个商品，那么就一定会将流量分到固定的一个应用nginx上面去。</p>
<h3 id="基于nginx-lua-java完成多级缓存架构的核心业务逻辑"><a href="#基于nginx-lua-java完成多级缓存架构的核心业务逻辑" class="headerlink" title="基于nginx+lua+java完成多级缓存架构的核心业务逻辑"></a>基于nginx+lua+java完成多级缓存架构的核心业务逻辑</h3><p>上面做了流量分发的demo测试，Java层级的缓存开发，接下来把他们对接起来，正式编写分发层和应用层的脚本。</p>
<p>eshop-cache03机器上修改流量分发层配置和lua脚本：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">vi hello.conf</span><br><span class="line"><span class="comment"># 添加以下内容</span></span><br><span class="line">location /product &#123;</span><br><span class="line">    default_type <span class="string">'text/html'</span>;</span><br><span class="line">    content_by_lua_file /usr/hello/lua/distribute.lua;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">cd</span> lua</span><br><span class="line">cp hello.lua distribute.lua</span><br><span class="line">vi distribute.lua</span><br><span class="line"><span class="comment"># 添加shopId</span></span><br><span class="line"><span class="built_in">local</span> shopId = uri_args[<span class="string">"shopId"</span>]</span><br><span class="line">requestPath = <span class="string">"/"</span>..requestPath..<span class="string">"?productId="</span>..productId..<span class="string">"&amp;shopId="</span>..shopId</span><br><span class="line"></span><br><span class="line">/usr/servers/nginx/sbin/nginx -s reload</span><br></pre></td></tr></table></figure>
<hr>
<p>修改应用层配置和lua脚本：</p>
<ol>
<li>应用nginx的lua脚本接收到请求</li>
<li>获取请求参数中的商品id，以及商品店铺id</li>
<li>根据商品id和商品店铺id，在nginx本地缓存中尝试获取数据</li>
<li><p>如果在nginx本地缓存中没有获取到数据，那么就到redis分布式缓存中获取数据，如果获取到了数据，还要设置到nginx本地缓存中</p>
<p> 这里有个问题，建议不要用nginx+lua直接去获取redis数据。因为openresty没有太好的redis cluster的支持包，所以建议是发送http请求到缓存数据生产服务，由该服务提供一个http接口。缓存数生产服务可以基于redis cluster api从redis中直接获取数据，并返回给nginx。</p>
</li>
<li><p>如果缓存数据生产服务没有在redis分布式缓存中没有获取到数据，那么就在自己本地ehcache中获取数据，返回数据给nginx，也要设置到nginx本地缓存中</p>
</li>
<li>如果ehcache本地缓存都没有数据，那么就需要去原始的服务中拉去数据，该服务会从mysql中查询，拉去到数据之后，返回给nginx，并重新设置到ehcache和redis中</li>
<li><p>nginx最终利用获取到的数据，动态渲染网页模板</p>
<p> 因为应用层也要访问http接口，所以也需要部署http依赖和模板的依赖</p>
 <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">cd</span> /usr/hello/lualib/resty/  </span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/	master/lib/resty/http_headers.lua  </span><br><span class="line">wget https://raw.githubusercontent.com/pintsized/lua-resty-http/master/lib/resty/http.lua </span><br><span class="line"><span class="built_in">cd</span> /usr/hello/lualib/resty/</span><br><span class="line">wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template.lua</span><br><span class="line">mkdir /usr/hello/lualib/resty/html</span><br><span class="line"><span class="built_in">cd</span> /usr/hello/lualib/resty/html</span><br><span class="line">wget https://raw.githubusercontent.com/bungle/lua-resty-template/master/lib/resty/template/html.lua</span><br></pre></td></tr></table></figure>
<p> 在hello.conf的server中配置模板位置</p>
 <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">set</span> <span class="variable">$template_location</span> <span class="string">"/templates"</span>;  </span><br><span class="line"><span class="built_in">set</span> <span class="variable">$template_root</span> <span class="string">"/usr/hello/templates"</span>;</span><br></pre></td></tr></table></figure>
<p> 编辑要显示的模板：</p>
 <figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">mkdir /usr/hello/templates</span><br><span class="line"><span class="built_in">cd</span> /usr/hello/templates</span><br><span class="line">vi product.html</span><br><span class="line"></span><br><span class="line">&lt;html&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">		&lt;meta http-equiv=<span class="string">"Content-Type"</span> content=<span class="string">"text/html; charset=UTF-8"</span>&gt;</span><br><span class="line">		&lt;title&gt;商品详情页&lt;/title&gt;</span><br><span class="line">	&lt;/head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">商品id: &#123;* productId *&#125;&lt;br/&gt;</span><br><span class="line">商品名称: &#123;* productName *&#125;&lt;br/&gt;</span><br><span class="line">商品图片列表: &#123;* productPictureList *&#125;&lt;br/&gt;</span><br><span class="line">商品规格: &#123;* productSpecification *&#125;&lt;br/&gt;</span><br><span class="line">商品售后服务: &#123;* productService *&#125;&lt;br/&gt;</span><br><span class="line">商品颜色: &#123;* productColor *&#125;&lt;br/&gt;</span><br><span class="line">商品大小: &#123;* productSize *&#125;&lt;br/&gt;</span><br><span class="line">店铺id: &#123;* shopId *&#125;&lt;br/&gt;</span><br><span class="line">店铺名称: &#123;* shopName *&#125;&lt;br/&gt;</span><br><span class="line">店铺评级: &#123;* shopLevel *&#125;&lt;br/&gt;</span><br><span class="line">店铺好评率: &#123;* shopGoodCommentRate *&#125;&lt;br/&gt;</span><br><span class="line">&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>将渲染后的网页模板作为http响应，返回给分发层nginx</p>
<p> 在<code>nginx.conf</code>的http模块里添加：</p>
 <figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># 添加nginx本地缓存的支持</span><br><span class="line">lua_shared_dict my_cache 128m;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<pre><code>修改`hello.conf`：


<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"># 添加路由</span><br><span class="line">location /product &#123;</span><br><span class="line">  	 default_type &apos;text/html&apos;;</span><br><span class="line">   	content_by_lua_file /usr/hello/lua/product.lua;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



修改lua/product.lua脚本，注意192.168.2.171是我本机的ip，启动了Java项目：


<figure class="highlight lua"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line">vi lua/product.lua</span><br><span class="line"><span class="keyword">local</span> uri_args = ngx.req.get_uri_args()</span><br><span class="line"><span class="keyword">local</span> productId = uri_args[<span class="string">"productId"</span>]</span><br><span class="line"><span class="keyword">local</span> shopId = uri_args[<span class="string">"shopId"</span>]</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> cache_ngx = ngx.shared.my_cache</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> productCacheKey = <span class="string">"product_info_"</span>..productId</span><br><span class="line"><span class="keyword">local</span> shopCacheKey = <span class="string">"shop_info_"</span>..shopId</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> productCache = cache_ngx:get(productCacheKey)</span><br><span class="line"><span class="keyword">local</span> shopCache = cache_ngx:get(shopCacheKey)</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> productCache == <span class="string">""</span> <span class="keyword">or</span> productCache == <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">	<span class="keyword">local</span> http = <span class="built_in">require</span>(<span class="string">"resty.http"</span>)</span><br><span class="line">	<span class="keyword">local</span> httpc = http.new()</span><br><span class="line"></span><br><span class="line">	<span class="keyword">local</span> resp, err = httpc:request_uri(<span class="string">"http://192.168.2.171:8080"</span>,&#123;</span><br><span class="line">  		method = <span class="string">"GET"</span>,</span><br><span class="line">  		<span class="built_in">path</span> = <span class="string">"/getProductInfo?productId="</span>..productId</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br><span class="line">	productCache = resp.body</span><br><span class="line">	cache_ngx:set(productCacheKey, productCache, <span class="number">10</span> * <span class="number">60</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> shopCache == <span class="string">""</span> <span class="keyword">or</span> shopCache == <span class="literal">nil</span> <span class="keyword">then</span></span><br><span class="line">	<span class="keyword">local</span> http = <span class="built_in">require</span>(<span class="string">"resty.http"</span>)</span><br><span class="line">	<span class="keyword">local</span> httpc = http.new()</span><br><span class="line"></span><br><span class="line">	<span class="keyword">local</span> resp, err = httpc:request_uri(<span class="string">"http://192.168.2.171:8080"</span>,&#123;</span><br><span class="line">  		method = <span class="string">"GET"</span>,</span><br><span class="line">  		<span class="built_in">path</span> = <span class="string">"/getShopInfo?shopId="</span>..shopId</span><br><span class="line">	&#125;)</span><br><span class="line"></span><br><span class="line">	shopCache = resp.body</span><br><span class="line">	cache_ngx:set(shopCacheKey, shopCache, <span class="number">10</span> * <span class="number">60</span>)</span><br><span class="line"><span class="keyword">end</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> cjson = <span class="built_in">require</span>(<span class="string">"cjson"</span>)</span><br><span class="line"><span class="keyword">local</span> productCacheJSON = cjson.decode(productCache)</span><br><span class="line"><span class="keyword">local</span> shopCacheJSON = cjson.decode(shopCache)</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> context = &#123;</span><br><span class="line">	productId = productCacheJSON.id,</span><br><span class="line">	productName = productCacheJSON.name,</span><br><span class="line">	productPrice = productCacheJSON.price,</span><br><span class="line">	productPictureList = productCacheJSON.pictureList,</span><br><span class="line">	productSpecification = productCacheJSON.specification,</span><br><span class="line">	productService = productCacheJSON.service,</span><br><span class="line">	productColor = productCacheJSON.color,</span><br><span class="line">	productSize = productCacheJSON.size,</span><br><span class="line">	shopId = shopCacheJSON.id,</span><br><span class="line">	shopName = shopCacheJSON.name,</span><br><span class="line">	shopLevel = shopCacheJSON.level,</span><br><span class="line">	shopGoodCommentRate = shopCacheJSON.goodCommentRate</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">local</span> template = <span class="built_in">require</span>(<span class="string">"resty.template"</span>)</span><br><span class="line">template.render(<span class="string">"product.html"</span>, context)</span><br></pre></td></tr></table></figure>


写到这里，应该去把java项目里的2个接口给补充一下。还是之前的项目：https://github.com/sail-y/eshop-cache
</code></pre><h3 id="分布式重建缓存的并发冲突问题"><a href="#分布式重建缓存的并发冲突问题" class="headerlink" title="分布式重建缓存的并发冲突问题"></a>分布式重建缓存的并发冲突问题</h3><p>之前在Java代码里会先去redis里面取数据，如果redis取不到，就会去ehcache里面取，如果还是取不到，就需要重建缓存了。</p>
<p>但是重建缓存有一个问题，因为我们的服务可能是多实例的，虽然在nginx层我们通过流量分发将请求通过id分发到了不同的nginx应用层上。那么到了接口服务层，可能多次请求访问的是不同的实例，那么可能会导致多个机器去重建读取相同的数据，然后写入缓存中，这就有了<strong>分布式重建缓存的并发冲突问题。</strong></p>
<p>问题就是可能2个实例获取到的数据快照不一样，但是新数据先写入缓存，如果这个时候另外一个实例的缓存后写入，就有问题了。</p>
<p><img src="/img/cache/多个缓存服务实例分布式重建的并发冲突问题.png" alt="多个缓存服务实例分布式重建的并发冲突问题"></p>
<p>这个问题有好几种解决方案：</p>
<ol>
<li>一样的在应用层对id进行取模然后固定分发到不同的服务实例上</li>
<li><p>将更新缓存的请求发送到同一个分区的kafka消息中</p>
<p> 一般来讲，每个服务实例都会监听kafka一个topic的某一个分区，所以具体去哪一个分区也得取模，保证是同一个实例消费到更新的请求。但问题是在nginx算出来的hash取模可能与kafka生产者的hash策略算出来的分区可能并不一致，还是可能有并发冲突问题。</p>
</li>
<li><p>基于zookeeper分布式锁的解决方案</p>
<p> 分布式锁，如果你有多个机器在访问同一个共享资源，加个锁让多个分布式的机器在访问共享资源的时候串行起来。</p>
</li>
</ol>
<h4 id="zk分布式锁的解决并发冲突的方案"><a href="#zk分布式锁的解决并发冲突的方案" class="headerlink" title="zk分布式锁的解决并发冲突的方案"></a>zk分布式锁的解决并发冲突的方案</h4><p><img src="/img/cache/基于zookeeper分布式锁的冲突解决方案.png" alt=""></p>
<ol>
<li>变更缓存重建以及空缓存请求重建，更新redis之前，都需要先获取对应商品id的分布式锁</li>
<li>拿到分布式锁之后，需要根据时间版本去比较一下，如果自己的版本新于redis中的版本，那么就更新，否则就不更新</li>
<li>如果拿不到分布式锁，那么就等待，不断轮询等待，直到自己获取到分布式的锁</li>
</ol>
<p>方案源码实现：<a href="https://github.com/sail-y/eshop-cache" target="_blank" rel="noopener">https://github.com/sail-y/eshop-cache</a></p>
<p><code>ZooKeeperSession.java</code></p>
<h2 id="经典的缓存-数据库读写的模式（cache-aside-pattern）"><a href="#经典的缓存-数据库读写的模式（cache-aside-pattern）" class="headerlink" title="经典的缓存+数据库读写的模式（cache aside pattern）"></a>经典的缓存+数据库读写的模式（cache aside pattern）</h2><ol>
<li><p>读的时候，先读缓存，缓存没有的话，那么就读数据库，然后取出数据后放入缓存，同时返回响应</p>
</li>
<li><p>更新的时候，先删除缓存，然后再更新数据库</p>
</li>
</ol>
<p><strong>为什么是删除缓存，而不是更新缓存呢？</strong></p>
<p>原因很简单，很多时候，复杂点的缓存的场景，因为缓存有的时候，不简单是数据库中直接取出来的值。比如商品详情页的系统，修改库存，只是修改了某个表的某些字段，但是要真正把这个影响的最终的库存计算出来，可能还需要从其他表查询一些数据，然后进行一些复杂的运算，才能最终计算出现在最新的库存是多少，然后才能将库存更新到缓存中去。</p>
<p>比如可能更新了某个表的一个字段，然后其对应的缓存，是需要查询另外两个表的数据，并进行运算，才能计算出缓存最新的值的，更新缓存的代价是很高的。还有一个问题就是，是不是每次修改数据库的时候，都一定要将其对应的缓存去跟新一份？也许有的场景是这样的，但是对于比较复杂的缓存数据计算的场景，就不是这样了。举个例子，一个缓存涉及的表的字段，在1分钟内就修改了20次，或者是100次，那么缓存更新20次，100次; 但是这个缓存在1分钟内就被读取了1次，系统有大量的冷数据，28法则，20%的数据，占用了80%的访问量。实际上，如果你只是删除缓存的话，那么1分钟内，访问的时候再计算，这个缓存不过就重新计算一次而已，开销大幅度降低。每次数据过来，就只是删除缓存，然后修改数据库，如果这个缓存，在1分钟内只是被访问了1次，那么只有那1次，缓存是要被重新计算的，用缓存才去算缓存。其实删除缓存，而不是更新缓存，就是一个lazy计算的思想，不要每次都重新做复杂的计算，不管它会不会用到，而是让它到需要被使用的时候再重新计算。</p>
<h2 id="缓存-数据库双写不一致问题分析"><a href="#缓存-数据库双写不一致问题分析" class="headerlink" title="缓存+数据库双写不一致问题分析"></a>缓存+数据库双写不一致问题分析</h2><h3 id="最初级的缓存不一致问题以及解决方案"><a href="#最初级的缓存不一致问题以及解决方案" class="headerlink" title="最初级的缓存不一致问题以及解决方案"></a>最初级的缓存不一致问题以及解决方案</h3><p>问题：先修改数据库，再删除缓存，如果删除缓存失败了，那么会导致数据库中是新数据，缓存中是旧数据，数据出现不一致</p>
<p>解决思路：</p>
<p>先删除缓存，再修改数据库，如果删除缓存成功了，如果修改数据库失败了，那么数据库中是旧数据，缓存中是空的，那么数据不会不一致，因为读的时候缓存没有，则读数据库中旧数据，然后更新到缓存中。</p>
<h3 id="比较复杂的数据不一致问题分析"><a href="#比较复杂的数据不一致问题分析" class="headerlink" title="比较复杂的数据不一致问题分析"></a>比较复杂的数据不一致问题分析</h3><p>数据发生了变更，先删除了缓存，然后要去修改数据库，此时还没修改。一个请求过来，去读缓存，发现缓存空了，去查询数据库，查到了修改前的旧数据，放到了缓存中，数据变更的程序完成了数据库的修改，这个时候数据库和缓存中的数据不一样了。</p>
<p><strong>为什么上亿流量高并发场景下，缓存会出现这个问题？</strong></p>
<p>只有在对一个数据在并发的进行读写的时候，才可能会出现这种问题。其实如果说你的并发量很低的话，特别是读并发很低，每天访问量就1万次，那么很少的情况下，会出现刚才描述的那种不一致的场景。但是问题是，如果每天的是上亿的流量，每秒并发读是几万，每秒只要有数据更新的请求，就可能会出现上述的数据库+缓存不一致的情况，高并发了以后，问题是很多的。</p>
<p>解决方案：</p>
<p><img src="/img/cache/复杂的数据库+缓存双写一致保障方案.png" alt=""></p>
<p><strong>数据库与缓存更新与读取操作进行异步串行化。</strong>更新数据的时候，根据数据的唯一标识（例如hash值取模），将操作路由之后，发送到一个jvm内部的队列中。读取数据的时候，如果发现数据不在缓存中，那么将重新读取数据+更新缓存的操作，根据唯一标识路由之后，也发送同一个jvm内部的队列中。一个队列对应一个工作线程，每个工作线程串行拿到对应的操作，然后一条一条的执行。</p>
<p>这里有一个优化点，一个队列中，其实多个更新缓存请求串在一起是没意义的，因此可以做过滤，如果发现队列中已经有一个更新缓存的请求了，那么就不用再放个更新请求操作进去了，直接等待前面的更新操作请求完成即可。待那个队列对应的工作线程完成了上一个操作的数据库的修改之后，才会去执行下一个操作，也就是缓存更新的操作，此时会从数据库中读取最新的值，然后写入缓存中。如果请求还在等待时间范围内，不断轮询发现可以取到值了，那么就直接返回; 如果请求等待的时间超过一定时长，那么这一次直接从数据库中读取当前的旧值。</p>
<p><strong>高并发的场景下，该解决方案要注意的问题</strong></p>
<ol>
<li><p>读请求长时阻塞</p>
<p> 由于读请求进行了非常轻度的异步化，所以一定要注意读超时的问题，每个读请求必须在超时时间范围内返回。该解决方案，最大的风险点在于可能数据更新很频繁，导致队列中积压了大量更新操作在里面，然后读请求会发生大量的超时，最后导致大量的请求直接走数据库，所以务必通过一些模拟真实的测试，看看更新数据的频繁是怎样的。</p>
<p> 另外一点，因为一个队列中，可能会积压针对多个数据项的更新操作，因此需要根据自己的业务情况进行测试，可能需要部署多个服务，每个服务分摊一些数据的更新操作。如果一个内存队列里居然会挤压100个商品的库存修改操作，每个库存修改操作要耗费10ms去完成，那么最后一个商品的读请求，可能等待10 * 100 = 1000ms = 1s后，才能得到数据，这个时候就导致读请求的长时阻塞。</p>
<p> 一定要做根据实际业务系统的运行情况，去进行一些压力测试和模拟线上环境，去看看最繁忙的时候，内存队列可能会挤压多少更新操作，可能会导致最后一个更新操作对应的读请求会hang多少时间，如果你计算过后，哪怕是最繁忙的时候，积压10个更新操作，最多等待200ms，那还可以。如果一个内存队列可能积压的更新操作特别多，那么就要加机器，让每个机器上部署的服务实例处理更少的数据，那么每个内存队列中积压的更新操作就会越少。</p>
<p> 一般来说数据的写频率是很低的，因此实际上正常来说，在队列中积压的更新操作应该是很少的，针对读高并发，读缓存架构的项目，一般写请求相对读来说，是非常非常少的，每秒的QPS能到几百就不错了。比如500/s的写操作，拆成5份，每200ms就是100个写操作，单机器一般20个内存队列，每个内存队列，可能就积压5个写操作，每个写操作性能测试后，一般在20ms左右就完成。如果写QPS扩大10倍，但是经过刚才的测算，就知道，单机支撑写QPS几百没问题，那么就扩容机器，扩容10倍的机器，10台机器，每个机器20个队列，200个队列。</p>
<p> 大部分的情况下，应该是大量的读请求过来，都是直接走缓存取到数据的。少量情况下，可能遇到读跟数据更新冲突的情况，如上所述，那么此时更新操作如果先入队列，之后可能会瞬间来了对这个数据大量的读请求，但是因为做了去重的优化，所以也就一个更新缓存的操作跟在它后面，等数据更新完了，读请求触发的缓存更新操作也完成，然后临时等待的读请求全部可以读到缓存中的数据。</p>
</li>
<li><p>读请求并发量过高</p>
<p> 还必须做好压力测试，确保恰巧碰上上述情况的时候，还有另一个风险，就是突然间大量读请求会在几十毫秒的延时hang在服务上，看服务能不能抗的住，需要多少机器才能抗住最大的极限情况的峰值。但是因为并不是所有的数据都在同一时间更新，缓存也不会同一时间失效，所以每次可能也就是少数数据的缓存失效了，然后那些数据对应的读请求过来，并发量应该也不会特别大。按1:99的比例计算读和写的请求，每秒5万的读QPS，可能只有500次更新操作，如果一秒有500的写QPS，那么要测算好，可能写操作影响的数据有500条，这500条数据在缓存中失效后可能导致多少读请求发送读请求到库存服务来要求更新缓存。一般来说这个比例在1:1，1:2，1:3之内，例如500条缓存数据失效导致每秒钟有1000个读请求会hang在库存服务上，每个读请求最多hang200ms就会返回。在同一时间最多hang住的可能也就是单机200个读请求，单机hang200个读请求，还是ok的。</p>
</li>
<li><p>多服务实例部署的请求路由</p>
<p> 可能这个服务部署了多个实例，那么必须保证，执行数据更新操作，以及执行缓存更新操作的请求，都通过nginx服务器路由到相同的服务实例上。</p>
</li>
<li><p>热点商品的路由问题，导致请求的倾斜</p>
<p> 万一某个商品的读写请求特别高，全部打到相同的机器的相同的队列里面去了，可能造成某台机器的压力过大。因为只有在商品数据更新的时候才会清空缓存，然后才会导致读写并发，所以更新频率不是太高的话，这个问题的影响并不是特别大，但是的确可能某些机器的负载会高一些。</p>
</li>
</ol>
<h3 id="复杂的数据库-缓存双写一致保障方案项目实例源码"><a href="#复杂的数据库-缓存双写一致保障方案项目实例源码" class="headerlink" title="复杂的数据库+缓存双写一致保障方案项目实例源码"></a>复杂的数据库+缓存双写一致保障方案项目实例源码</h3><p><a href="https://github.com/sail-y/eshop-inventory" target="_blank" rel="noopener">https://github.com/sail-y/eshop-inventory</a></p>

      
    </div>

    

    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/img/donate/wechatpay.jpeg" alt="杨帆 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/img/donate/alipay.jpeg" alt="杨帆 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/多级缓存架构/" rel="tag"># 多级缓存架构</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/12/cache02/" rel="next" title="高可用缓存架构实战2-Redis企业级应用实战">
                <i class="fa fa-chevron-left"></i> 高可用缓存架构实战2-Redis企业级应用实战
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/02/20/cache04-2/" rel="prev" title="zookeeper+kafka集群的安装部署">
                zookeeper+kafka集群的安装部署 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8yOTk2Ni82NTMx"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/img/photo/bug.png"
                alt="杨帆" />
            
              <p class="site-author-name" itemprop="name">杨帆</p>
              <p class="site-description motion-element" itemprop="description">记录工作和学习中遇到的问题</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">107</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">18</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">38</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/sail-y" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://weibo.com/338632221" target="_blank" title="微博"><i class="fa fa-fw fa-globe"></i>微博</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#上亿流量的商品详情页系统的多级缓存架构"><span class="nav-number">1.</span> <span class="nav-text">上亿流量的商品详情页系统的多级缓存架构</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#多级缓存架构中每一层的意义"><span class="nav-number">1.1.</span> <span class="nav-text">多级缓存架构中每一层的意义</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多级缓存架构项目实例源码"><span class="nav-number">1.2.</span> <span class="nav-text">多级缓存架构项目实例源码</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Nginx层缓存"><span class="nav-number">1.3.</span> <span class="nav-text">Nginx层缓存</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#部署第一个nginx，作为应用层nginx"><span class="nav-number">1.3.1.</span> <span class="nav-text">部署第一个nginx，作为应用层nginx</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#部署openresty"><span class="nav-number">1.3.2.</span> <span class="nav-text">部署openresty</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nginx-lua开发的hello-world"><span class="nav-number">1.3.3.</span> <span class="nav-text">nginx+lua开发的hello world</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#工程化的nginx-lua项目结构"><span class="nav-number">1.3.4.</span> <span class="nav-text">工程化的nginx+lua项目结构</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#开发和部署流量分发层"><span class="nav-number">1.3.5.</span> <span class="nav-text">开发和部署流量分发层</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#基于nginx-lua-java完成多级缓存架构的核心业务逻辑"><span class="nav-number">1.4.</span> <span class="nav-text">基于nginx+lua+java完成多级缓存架构的核心业务逻辑</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#分布式重建缓存的并发冲突问题"><span class="nav-number">1.5.</span> <span class="nav-text">分布式重建缓存的并发冲突问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#zk分布式锁的解决并发冲突的方案"><span class="nav-number">1.5.1.</span> <span class="nav-text">zk分布式锁的解决并发冲突的方案</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#经典的缓存-数据库读写的模式（cache-aside-pattern）"><span class="nav-number">2.</span> <span class="nav-text">经典的缓存+数据库读写的模式（cache aside pattern）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#缓存-数据库双写不一致问题分析"><span class="nav-number">3.</span> <span class="nav-text">缓存+数据库双写不一致问题分析</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#最初级的缓存不一致问题以及解决方案"><span class="nav-number">3.1.</span> <span class="nav-text">最初级的缓存不一致问题以及解决方案</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#比较复杂的数据不一致问题分析"><span class="nav-number">3.2.</span> <span class="nav-text">比较复杂的数据不一致问题分析</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#复杂的数据库-缓存双写一致保障方案项目实例源码"><span class="nav-number">3.3.</span> <span class="nav-text">复杂的数据库+缓存双写一致保障方案项目实例源码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">杨帆</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动 v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Gemini</a> v6.1.0</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv" title="总访客量">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
    </span>
  

  
    <span class="site-pv" title="总访问量">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
    </span>
  
</div>









        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  



  
  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.1.0"></script>



  



	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  










  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  

</body>
</html>
